package com.yjy.shmily;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import androidx.annotation.RequiresApi;

/**
 * author : YangJinyang
 * create : 2019-10-28 15:45
 * description :切换主题，动画view
 */
public class RippleAnimation extends View {

    private ViewGroup mRootView;
    private Context mContext;

    private float startX;

    private float sratrY;

    private int radius;

    private Paint mPaint;

    private int mMaxRadius;

    private int mStartRadius;

    private boolean isStarted;

    private Bitmap mBackground;

    private int mDuration = 1000;//动画持续时间，默认2s
    private AnimatorListenerAdapter mAnimatorListener;
    private ValueAnimator.AnimatorUpdateListener mAnimatorUpdateListener;
    private OnAnimationEndListener mOnAnimationEndListener;
    private int mCurrentRadius;


    private RippleAnimation(Context mContext, float startX, float sratrY, int radius) {
        super(mContext);
        mRootView = (ViewGroup) ((Activity) mContext).getWindow().getDecorView();
        this.mContext = mContext;
        this.startX = startX;
        this.sratrY = sratrY;
        this.radius = radius;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);//抗锯齿
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        //这里设置点击事件，是为了防止在动画进行的过程中切断动画，说白了是将点击事件拦截一下
        setOnClickListener();
        updateMaxRadius();
        initListener();
    }

    public static RippleAnimation create(View clickView) {
        Context context = clickView.getContext();
        int newWidth = clickView.getWidth() / 2;
        int newHeight = clickView.getHeight() / 2;
        //起始半径
        float startX = getAbsoluteX(clickView) + newWidth;
        float startY = getAbsoluteY(clickView) + newHeight;

        //起始半径
        //因为我们要避免遮挡按钮
        int radius = Math.max(newWidth, newHeight);
        return new RippleAnimation(context, startX, startY, radius);
    }


    private void updateMaxRadius() {

        //将屏幕分成4个小矩形
        RectF leftTop = new RectF(0, 0, startX + mStartRadius, sratrY + mStartRadius);
        RectF rightTop = new RectF(leftTop.right, 0, mRootView.getRight(), leftTop.bottom);
        RectF leftBottom = new RectF(0, leftTop.bottom, leftTop.right, mRootView.getBottom());
        RectF rightBottom = new RectF(leftBottom.right, leftTop.bottom, mRootView.getRight(), leftBottom.bottom);
        //分别获取对角线长度
        double leftTopHypotenuse = Math.sqrt(Math.pow(leftTop.width(), 2) + Math.pow(leftTop.height(), 2));
        double rightTopHypotenuse = Math.sqrt(Math.pow(rightTop.width(), 2) + Math.pow(rightTop.height(), 2));
        double leftBottomHypotenuse = Math.sqrt(Math.pow(leftBottom.width(), 2) + Math.pow(leftBottom.height(), 2));
        double rightBottomHypotenuse = Math.sqrt(Math.pow(rightBottom.width(), 2) + Math.pow(rightBottom.height(), 2));
        //取最大值
        mMaxRadius = (int) Math.max(
                Math.max(leftTopHypotenuse, rightTopHypotenuse),
                Math.max(leftBottomHypotenuse, rightBottomHypotenuse));

    }


    /**
     * 获取view在屏幕中的绝对x坐标
     */
    private static float getAbsoluteX(View view) {
        float x = view.getX();
        ViewParent parent = view.getParent();
        if (parent != null && parent instanceof View) {
            x += getAbsoluteX((View) parent);
        }
        return x;
    }

    /**
     * 获取view在屏幕中的绝对y坐标
     */
    private static float getAbsoluteY(View view) {
        float y = view.getY();
        ViewParent parent = view.getParent();
        if (parent != null && parent instanceof View) {
            y += getAbsoluteY((View) parent);
        }
        return y;
    }


    /**
     * 开启动画
     */
    public void start() {
        if (!isStarted) {
            isStarted = true;
            updateBackground();
            attachToRootView();
            getAnimator().start();
        }
    }


    /**
     * 更新屏幕截图
     */
    private void updateBackground() {
        if (mBackground != null && !mBackground.isRecycled()) {
            mBackground.recycle();
        }
        mRootView.setDrawingCacheEnabled(true);
        mBackground = mRootView.getDrawingCache();
        mBackground = Bitmap.createBitmap(mBackground);
        mRootView.setDrawingCacheEnabled(false);
    }

    /**
     * 添加到根视图
     */
    private void attachToRootView() {
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mRootView.addView(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //在新的图层上面绘制
        int layer = canvas.saveLayer(0, 0, getWidth(), getHeight(), null);
        canvas.drawBitmap(mBackground, 0, 0, null);
        canvas.drawCircle(startX, sratrY, mCurrentRadius, mPaint);
        canvas.restoreToCount(layer);
    }


    private ValueAnimator getAnimator() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mMaxRadius).setDuration(mDuration);
        valueAnimator.addUpdateListener(mAnimatorUpdateListener);
        valueAnimator.addListener(mAnimatorListener);
        return valueAnimator;
    }

    private void initListener() {
        mAnimatorListener = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //动画播放完毕, 移除本View
                detachFromRootView();
                if (mOnAnimationEndListener != null) {
                    mOnAnimationEndListener.onAnimationEnd();
                }
                isStarted = false;
            }
        };
        mAnimatorUpdateListener = new ValueAnimator.AnimatorUpdateListener() {


            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //更新圆的半径
                mCurrentRadius = (int) (float) animation.getAnimatedValue() + mStartRadius;
                postInvalidate();
            }
        };
    }

    public RippleAnimation setmOnAnimationEndListener(OnAnimationEndListener mOnAnimationEndListener) {
        this.mOnAnimationEndListener = mOnAnimationEndListener;
        return this;
    }

    /**
     * 从根视图中移除
     */
    private void detachFromRootView() {
        mRootView.removeView(this);
    }

    public void setOnClickListener() {
        super.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    public interface OnAnimationEndListener {
        void onAnimationEnd();

    }
}
